<template>
  <div>
    <van-search
      v-model="keywords"
      show-action
      placeholder="搜索鲜花、蛋糕、礼品"
      @search="onSearch"
      shape="round"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <div class="history">
      <div class="his-top">
        <h4>历史记录</h4>
        <img src="@/assets/imgs/qingkong.png" alt="" @click ='clearHis'/>
      </div>
      <div v-if="!history.length" class="zanwu">
          暂无搜索记录
      </div>
      <div class="his-bot" v-if ="history.length" @click='History(history)'>
        <span v-for="item in history" :key='item'>{{item}}</span>
      </div>
    </div>
    <div class="history">
      <div class="his-top">
        <h4>热门搜索</h4>
        <img src="@/assets/imgs/eyes.png" alt="" />
      </div>
      <div class="his-bot">
        <span>爱情鲜花</span>
        <span>向日葵</span>
        <span>生日蛋糕</span>
        <span>玫瑰</span>
        <span>百合</span>
        <span>满天星</span>
        <span>康乃馨</span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      keywords: '',
      history: localStorage.getItem('history') ? JSON.parse(localStorage.getItem('history')) : []
    }
  },
  methods: {
    clearHis () {
      localStorage.removeItem('history')
      location.reload()
    },
    onSearch () {
      let history = localStorage.getItem('history') ? JSON.parse(localStorage.getItem('history')) : []
      history.unshift(this.keywords)
      // 数组去重 es6
      history = [...new Set(history)]
      // 历史记录长度
      if (history.length >= 5) {
        history.length = 5
      }
      // 每搜索一次，就存储一次
      localStorage.setItem('history', JSON.stringify(history))
      this.$router.push({
        path: '/searchResult',
        query: {
          word: this.keywords
        }
      })
    },
    History (his) {
      this.keywords = his
      this.onSearch()
    }
  }
}
</script>

<style lang="scss" scoped>
.zanwu{
    font-size: 13px;
}
.van-search {
  position: relative;
  border-bottom: 1px solid #ddd;
  /deep/.van-search__content {
    border-radius: 15px;
  }
  .van-icon-search {
    font-size: 20px;
  }
}
.history {
  background: #fff;
  padding: 10px;
  .his-top {
    display: flex;
    justify-content: space-between;
  }
  .his-bot {
    span {
      font-size: 13px;
      padding: 5px;
      background: #eee;
      border-radius: 3px;
      margin: 10px;
      line-height: 33px;
    }
  }
}
</style>
